package com.tansun.rule.convertor;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.xml.bind.annotation.adapters.XmlAdapter;
/**
 * 
 * @author WanYe
 * JAXB 日期转换
 *
 */
public class JaxbDateAdapter extends XmlAdapter<String, Date> {

	static final String STANDARM_DATE_FORMAT_LONG = "yyyy-MM-dd HH:mm:ss";
	static final String matcherLong = "\\d\\d\\d\\d-\\d\\d-\\d\\d \\d\\d:\\d\\d:\\d\\d";
	static final String STANDARM_DATE_FORMAT_NORM = "yyyy-MM-dd";
	static final String matcherNorm = "\\d\\d\\d\\d-\\d\\d-\\d\\d";
	static final String STANDARM_DATE_FORMAT_SHOR = "yyyy-MM";
	static final String matcherShor = "\\d\\d\\d\\d-\\d\\d";
	
	@Override
	public String marshal(Date d) throws Exception {
		DateFormat format = new SimpleDateFormat(STANDARM_DATE_FORMAT_LONG);
		 return format.format(d);
	}

	@Override
	public Date unmarshal(String v) throws Exception {
		 if (v == null) {
			return null;
		}
			 
		DateFormat format = null;
		if(v.matches(matcherLong)){
			format = new SimpleDateFormat(STANDARM_DATE_FORMAT_LONG);
		}
		if(v.matches(matcherNorm)){
			format = new SimpleDateFormat(STANDARM_DATE_FORMAT_NORM);
		}
		if(v.matches(matcherShor)){
			format = new SimpleDateFormat(STANDARM_DATE_FORMAT_SHOR);
		}
		if(format == null){
			return null;
		} else {
			return format.parse(v);
		}
	}
	public static void main(String[] args) {
		if("2100-11-11 12:12:12".matches("\\d\\d\\d\\d-\\d\\d-\\d\\d \\d\\d:\\d\\d:\\d\\d")){
			System.out.println("fasdf");
		}
		
	}

}
